package web.synchorichned;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author ZhangGJ
 * @Date 2022/02/07 13:57
 */
@Slf4j
@RestController
@RequestMapping("sync")
public class SynchronizedController6 {

    private final SynchronizedKey synchronizedKey;

    @Autowired
    public SynchronizedController6(SynchronizedKey synchronizedKey) {
        this.synchronizedKey = synchronizedKey;
    }

    @GetMapping("process6")
    public String process(String orderId) {
        synchronizedKey.exec(orderId, () -> {
            log.info("=======Start: {}", orderId);
            service(orderId);
            log.info("=======End: {}", orderId);
        });
        return "Success!";
    }

    public void service(String orderId) {
        try {
            Thread.sleep(3000L);
            log.info("=====================执行了: {}", orderId);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}


@Component
class SynchronizedKey {
    Map<String, ReentrantLock> mutexCache = new ConcurrentHashMap<>();

    public void exec(String key, Runnable statement) {
        ReentrantLock mutex4Key = mutexCache.computeIfAbsent(key, k -> new ReentrantLock());
        mutex4Key.lock();
        try {
            statement.run();
        } finally {
            if (mutex4Key.getQueueLength() == 0) {
                mutexCache.remove(key);
            }
            mutex4Key.unlock();
        }
    }
}
